package com.tomdd.controller;

import cn.hutool.core.bean.BeanUtil;
import com.tomdd.model.entity.User;
import com.tomdd.model.req.UpdateUserReq;
import com.tomdd.model.resp.Result;
import com.tomdd.service.UserService;
import com.tomdd.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.Setter;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 用户控制类
 *
 * @author zx
 * @date 2024-07-17 21:43
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Setter(onMethod_ = @Autowired)
    private UserService userService;


    /**
     * 用户注册
     *
     * @param username 用户名
     * @param password 用户密码
     * @return {@link Result}
     */
    @PostMapping("/register")
    public Result register(
            @Pattern(regexp = "^\\S{5,16}$") String username,
            @Pattern(regexp = "^\\S{5,16}$") String password) {
        return userService.register(username, password);
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 用户密码
     * @return 登录成功, 返回token
     */
    @PostMapping("/login")
    public Result<String> login(
            @Pattern(regexp = "^\\S{5,16}$") String username,
            @Pattern(regexp = "^\\S{5,16}$") String password) {
        return userService.login(username, password);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息 {@link User}
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        // 根据用户名查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     *
     * @param userReq 更新用户信息
     * @return 响应结果
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated UpdateUserReq userReq) {
        User user = BeanUtil.copyProperties(userReq, User.class);
        userService.updateById(user);
        return Result.success();
    }


    /**
     * 跟新用户头像
     *
     * @param avatarUrl 用户头像
     * @return
     */
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        return userService.updateAvatar(avatarUrl);
    }

    /**
     * 更新密码
     *
     * @param params key: old_pwd 旧密码; new_pwd 新密码; re_pwd 确认新密码
     * @param token  token
     * @return 更新成功返回Result.success() ; 反之返回Result.error()
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        return userService.updatePwd(params, token);
    }


}
